package com.yitiao.multithread.completablefuture;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

public class CompletableFutureDemo {
    public static void main(String[] args) {
//        testException();
        testAsync();
    }

    private static void testException() {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                    System.out.println(Thread.currentThread().getName());  // ForkJoinPool.commonPool-worker-1
                    return 10 / 0;
                })
                .handle((result, throwable) -> {
            System.out.println("handle:"+result);
            if (throwable!=null){
                System.out.println(throwable.getMessage());
            }
            return result;
        });
//                .whenComplete((result, throwable) ->
//                        System.out.println(result)
//                );
//                .exceptionally(throwable -> {
//                    System.out.println("exceptionally>>>" + throwable.getMessage());
//                    return null;
//                });

        try {
            completableFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    private static void testAsync(){
        List<String> list = Lists.newArrayList("1", "2", "3");
        List<Void> voidList = list.stream().map(l -> CompletableFuture.runAsync(() -> {
            System.out.println("开始执行任务:" + l + Thread.currentThread().getName());
            try {
                // 模拟某个任务抛出异常
//                if (l.equals("2")){
//                    int a = 10/0;
//                }
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("结束执行任务:" + l + Thread.currentThread().getName());
        })).collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList());
        System.out.println("all finish");
    }
}
